package com.ruoyi.api.user;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.ruoyi.api.cache.ICacheService;
import com.ruoyi.api.user.requestVo.UserWxPayRequestVo;
import com.ruoyi.api.util.DateUtil;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.user.domain.Order;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.service.IOrderService;
import com.ruoyi.user.service.IUserService;

import io.swagger.annotations.ApiOperation;

/**
 * APP微信授权操作处理
 * @author ruoyi
 * @date 2018-12-14
 */
@Controller
@RequestMapping("/api/alipay")
public class ApiAlipayController extends BaseController
{
	
	private static final Logger log = LoggerFactory.getLogger(ApiAlipayController.class);
	
    private String prefix = "api:alipay";
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IOrderService orderService;
	
	/**
     * 支付宝统一下单接口
     * @return
     */
	@ResponseBody
	@PostMapping("/doOrder")
	@ApiOperation(value="支付宝统一下单", notes="支付宝统一下单",produces = "application/json")
    public Map<String, Object> doOrder(HttpServletRequest request, @RequestBody UserWxPayRequestVo payRequestVo) {
		//实例化客户端
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "2019012163100239", "MIIEvg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fmRwKBgDSDl9PD1DhD8QUF2zpiV7ImMFYlDghxXNuw8U2qOTv4+3m+87Xw96LaYjXGVKHKNsXk3bxeh0R10fMvs9OmF4ql2qcTnVvqhVaRfkeZMyM4m96wj94aWaoka/8XNzAJ1wNllGCdF6iNsJ+HDv6rt+smVrjS6ROf/uNloOScVXgnAoGBAK8WSeQdKXvDPpmHlNYHtmseO48zu9U8PtQlYRk4nfZWXVYxWkBNx3gzqX8WU2+U930mRMKlAwzVuTjwTFe462QiXYG9sL3OvxDlzsmaXmwmq1Aeq8jahejyvzIiV00pphgYv2TL9WxAyMaNVpW8KymdTTE0vLCfPvkRBiqIcvV3AoGBAIsfWehR1fkPY5uLfbX2e3+ccvRt6ein9RBr3RO0uDRm0AnBzibrGqlTCIrobZco+0eiAZktS/yEf2Q9bPszcVk/q2mJyDeqBdMptXQ5EYwX8lSGx0uhHXJTlHV7HN/rbO29H/WBpNVINdE0YxLZ9yxn5mbm3p2uWEtzJqaXDoXK", "json", "UTF-8", 
				"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk1ySrOdQJF7QH2hYFhN+Fvun8OUa1+qWr0U8W8XbnHCFIRuP2Obr/YodPaSOk99OTV+w5qLoCFZd/d93SpiwEdrvtObJiBWEFUW89luzBzAWHJKgjPAHpIsG/dfozZFimSO+7Xbcx4jgcmGs4P8O3evinA/y4eZ7Yva/2oyqjlK5HHcwejXHSU6Ik2OMlmSympWemQaXediCCkm12YDwqteaMfjlZD6LRsm//bpyTnqpsIwPdQNtgnOjcKpELsLIqdcYIGNlJmSHAR6OzbwWMiIhBoaEYiGfSJcQmSi3HIsBsz2o5SKC/0yOswvgwr8hKyOZEbcqg0QnNWfU0HD5KwIDAQAB", "RSA2");
		//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
		AlipayTradeAppPayRequest requestAlipay = new AlipayTradeAppPayRequest();
		//SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		String out_trade_no = DateUtil.genOrderNum();
		BigDecimal a = new BigDecimal(payRequestVo.getAmount());
		BigDecimal b = new BigDecimal(100);
		model.setBody(payRequestVo.getContent());
		model.setSubject("安+平台-会员充值");
		model.setOutTradeNo(out_trade_no);
		model.setTimeoutExpress("30m");
		model.setTotalAmount(String.valueOf(a.divide(b, 2, RoundingMode.HALF_UP)));
		model.setProductCode("AN_VIP");
		requestAlipay.setBizModel(model);
		//requestAlipay.setNotifyUrl("http://47.52.113.233/api/alipay/payNotifyUrl");
		requestAlipay.setNotifyUrl("http://47.93.23.253:8090/api/alipay/payNotifyUrl");
		try {
	        //这里和普通的接口调用不同，使用的是sdkExecute
	        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(requestAlipay);
	        System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
	        Order order = new Order();
        	User user = (User) request.getAttribute("user");
        	order.setContent(payRequestVo.getContent());
        	order.setMonths(payRequestVo.getMonths());
        	order.setAmount(payRequestVo.getAmount());
        	order.setCreateTime(new Date());
        	order.setOrderNum(out_trade_no);
        	order.setStatus(1);
        	order.setTpye(2);
        	order.setUserId(user.getId());
        	order.setTtype(payRequestVo.getType());
        	orderService.insertOrder(order);
        	return successApp(response.getBody());
	    } catch (AlipayApiException e) {
	        e.printStackTrace();
	        return errorApp("alipay-00001", "支付宝生产订单失败");
		}
    }
    
    @ResponseBody
	@PostMapping("/payNotifyUrl")
	@ApiOperation(value="支付宝支付异步结果通知", notes="支付宝支付异步结果通知",produces = "application/json")
    public String payNotifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	//获取支付宝POST过来反馈信息
    	Map<String,String> params = new HashMap<String,String>();
    	Map requestParams = request.getParameterMap();
    	for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
    	    String name = (String) iter.next();
    	    String[] values = (String[]) requestParams.get(name);
    	    String valueStr = "";
    	    for (int i = 0; i < values.length; i++) {
    	        valueStr = (i == values.length - 1) ? valueStr + values[i]
    	                    : valueStr + values[i] + ",";
    	  	}
    	    //乱码解决，这段代码在出现乱码时使用。
    		//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
    		params.put(name, valueStr);
    	}
    	//切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
    	//boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
    	boolean flag = AlipaySignature.rsaCheckV1(params, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk1ySrOdQJF7QH2hYFhN+Fvun8OUa1+qWr0U8W8XbnHCFIRuP2Obr/YodPaSOk99OTV+w5qLoCFZd/d93SpiwEdrvtObJiBWEFUW89luzBzAWHJKgjPAHpIsG/dfozZFimSO+7Xbcx4jgcmGs4P8O3evinA/y4eZ7Yva/2oyqjlK5HHcwejXHSU6Ik2OMlmSympWemQaXediCCkm12YDwqteaMfjlZD6LRsm//bpyTnqpsIwPdQNtgnOjcKpELsLIqdcYIGNlJmSHAR6OzbwWMiIhBoaEYiGfSJcQmSi3HIsBsz2o5SKC/0yOswvgwr8hKyOZEbcqg0QnNWfU0HD5KwIDAQAB", "UTF-8","RSA2");
    	if(flag){
            if("TRADE_SUCCESS".equals(params.get("trade_status"))){
                //付款金额
                //String amount = params.get("buyer_pay_amount");
                //商户订单号
                String out_trade_no = params.get("out_trade_no");
                //支付宝交易号
                String trade_no = params.get("trade_no");
                //附加数据
                //String passback_params = URLDecoder.decode(params.get("passback_params"));
                Order param = new Order();
            	param.setOrderNum(out_trade_no);
            	param.setStatus(1);
            	List<Order> list = orderService.selectOrderList(param);
            	if(list!=null&&list.size()>0){
            		Order order = list.get(0);
            		order.setStatus(2);
            		order.setPayid(trade_no);
            		orderService.updateOrder(order);
            		User user = userService.selectUserById(order.getUserId());
            		if(user!=null){
            			if(user.getIsVip()!=null&&user.getIsVip()!=1){
            				user.setIsVip(1);
            				user.setVipType(order.getTtype());
            				user.setVipTime(DateUtil.addMonthsToDate(new Date(), order.getMonths()));
            			}else{
            				user.setVipType(order.getTtype());
            				user.setVipTime(DateUtil.addMonthsToDate(user.getVipTime(), order.getMonths()));
            			}
            			userService.updateUser(user);
            		}
            	}
            }
        }
        return "success";
    }

}
